package com.rms.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rms.common.Const;
import com.rms.utils.StringUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.rms.entity.Food;
import com.rms.entity.FoodType;

import com.rms.service.IFoodService;
import com.rms.service.IFoodTypeService;
import com.rms.utils.PageBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/food")
public class FoodAction extends BaseAction {


    @RequestMapping(value = "/list")
    public String list(String currentPage, HttpServletRequest request) {

        try {
            // 1. 获取“当前页”参数； (第一次访问当前页为null)

            // 判断
            if (StringUtils.isNull(currentPage)) {
                currentPage = "1"; // 第一次访问，设置当前页为1;
            }
            // 转换
            int currentPageI = Integer.parseInt(currentPage);

            // 2. 创建PageBean对象，设置当前页参数； 传入service方法参数
            PageBean<Food> pageBean = new PageBean<Food>();
            pageBean.setCurrentPage(currentPageI);

            // 3. 调用service
            foodService.getAll(pageBean); // 【pageBean已经被dao填充了数据】
            // 4. 保存pageBean对象，到request域中

            List<Food> list = pageBean.getPageData();
            // 获得食物类别的方法
            List<FoodType> types = new ArrayList<FoodType>();

            if (list != null) {
                for (Food food : list) {
                    FoodType foodtype = foodTypeService.findById(food.getFoodType_id());
                    types.add(foodtype);
                }
            }
            request.setAttribute("types", types);

            request.setAttribute("pageBean", pageBean);
            request.setAttribute("list", list);
            return "/sys/food/foodList.jsp";
        } catch (Exception e) {
            e.printStackTrace(); // 测试使用
            // 出现错误，跳转到错误页面；给用户友好提示
            return "redirect:/error/error.jsp";
        }

    }


    @RequestMapping(value = "/findFoodType")
    public String findFoodType(Model model) {
        List<FoodType> foodtypes = foodTypeService.query();
        model.addAttribute("foodtypes", foodtypes);
        return "/sys/food/saveFood.jsp";
    }

    @RequestMapping(value = "/add")
    private String add(String currentPage,
                       @RequestParam(value = "img", required = false)
                       MultipartFile img, HttpServletRequest request) {
        try {

            Food food = new Food();
            Map<String, String[]> map = request.getParameterMap();
            BeanUtils.populate(food,map);

            String path = request.getServletContext()
                    .getRealPath("/upload");

            if(img!=null){

                File f = new File(path);
                if (!f.exists()) {
                    f.mkdir();
                }
                String name = img.getOriginalFilename();
                if (!StringUtils.isNull(name)) {
                    BeanUtils.setProperty(food, "img",
                            "upload/" + name);

                    // a2. 拼接文件名
                    File imgFile = new File(path, name);
                    // d. 上传
                    //保存
                    try {
                        img.transferTo(imgFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            foodService.add(food);
            return list(currentPage, request);

        } catch (Exception e) {
            e.printStackTrace();
            return Const.ON_ERROR_JSP;
        }
    }

    @RequestMapping("/query")
    public String query(Model model, HttpServletRequest request) {
        try {
            List<Food> list = foodService.query();
            request.setAttribute("list", list);

            // 获得食物类别的方法
            List<FoodType> types = new ArrayList<FoodType>();

            for (Food food : list) {
                FoodType foodtype = foodTypeService.findById(food.getFoodType_id());
                types.add(foodtype);
            }
            request.setAttribute("types", types);

            return "/sys/food/foodList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return Const.ON_ERROR_JSP;
        }
    }

    @RequestMapping(value = "/update")
    public String update(String currentPage,
                         @RequestParam(value = "img", required = false)
                                 MultipartFile img,
                         HttpServletRequest request) {
        try {

            Food food = new Food();
            Map<String, String[]> map = request.getParameterMap();
            BeanUtils.populate(food, map);

            if(img!=null) {
                String path = request.getServletContext()
                        .getRealPath("/upload");
                File f = new File(path);
                if (!f.exists()) {
                    f.mkdir();
                }
                String name = img.getOriginalFilename();
                if (!StringUtils.isNull(name)) {
                    BeanUtils.setProperty(food, "img",
                            ("upload/" + name));

                    // a2. 拼接文件名
                    File imgFile = new File(path, name);
                    // d. 上传
                    //保存
                    try {
                        img.transferTo(imgFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    int id = food.getId();
                    String imgName = foodService.findById(id).getImg();
                    BeanUtils.setProperty(food, "img", img);
                }
            }
            foodService.updata(food);
            return list(currentPage, request);

        } catch (Exception e) {
            e.printStackTrace();
            return Const.ON_ERROR_JSP;
        }

    }


    @RequestMapping(value = "/delete")
    public String delete(int id, String currentPage, HttpServletRequest request) {
        try {

            foodService.delete(id);
            return list(currentPage, request);
        } catch (Exception e) {
            e.printStackTrace();
            return Const.ON_ERROR_JSP;
        }
    }

    @RequestMapping(value = "/search")
    public String search(String keyword, String currentPage, HttpServletRequest request) {
        try {

            if (StringUtils.isNull(keyword))
                return list(currentPage, request);

            List<Food> list = foodService.query(keyword);
            List<FoodType> types = new ArrayList<FoodType>();

            if (list != null) {
                for (Food food : list) {
                    FoodType foodtype = foodTypeService.findById(food.getFoodType_id());
                    types.add(foodtype);
                }
            }
            request.setAttribute("types", types);
            request.setAttribute("list", list);
            return "/sys/food/foodList.jsp";

        } catch (Exception e) {
            return Const.ON_ERROR_JSP;
        }

    }

    // 这个方法没用
    @RequestMapping(value = "/show")
    public String show(int id, Model model, HttpServletRequest request, HttpServletResponse response) {
        findFoodType(model);

        Food food = foodService.findById(id);

        request.setAttribute("food", food);
        // 得到食物里面的食物类型ID
        int foodType_id = food.getFoodType_id();

        // 通过
        FoodType type = foodTypeService.findById(foodType_id);
        request.setAttribute("type", type);

        return "/sys/food/updateFood.jsp";
    }
}
